package jb.astronomy.project;


/*Ioannis A. Bouhras - DSCArduino Telescope bluetooth Controller - GPL3*/

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URI;
import java.util.ArrayList;
import java.util.UUID;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.provider.Settings;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;


public class DSCArduinoActivity extends Activity implements OnClickListener, OnItemClickListener{

/*used for GPS Information*/
static TextView textLatitude;
static TextView textLongitude;

/*BT Messages*/		
public static final int MESSAGE_READ = 2;
public static final int MESSAGE_STATE_CHANGE = 1;
	 
// Constants that indicate the current connection state
public static final int STATE_NONE = 0;       // we're doing nothing
public static final int STATE_LISTEN = 1;     // now listening for incoming connections
public static final int STATE_CONNECTING = 2; // now initiating an outgoing connection
public static final int STATE_CONNECTED = 3;  // now connected to a remote device

/*Hardcoded Arduino BT address here. Must pass it to UI later*/
//final static String	     ROBO_BTADDR = "00:11:12:31:03:53";
//final String	     ROBO_BTADDR = "00:11:12:31:03:53";



//-- debugging --//	
String	LOG_TAG = "DSCArduino";

//-- GUI --//
final static String	m_szAppTitle = "DSCArduino";

ProgressDialog	m_progDlg;
	
TextView	m_tvD1, m_tvD2;
	

public static final int idLVFirstItem = Menu.FIRST + 100;

//-- Bluetooth functionality --//
	
final static int              MAX_DEVICES = 50;
	 
BluetoothAdapter 		m_BluetoothAdapter;
boolean	                       m_ASDKScanRunning = false;
int			     m_nDiscoverResult = -1;
int			     m_nRoboDev = -1;

// Intent request codes
final int 		     REQUEST_CONNECT_DEVICE = 1,
   				REQUEST_ENABLE_BT = 2;
BluetoothSocket 		m_btSck; //used to handle Android<->Robot communication
private static final UUID    SPP_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
Thread				m_hReadThread;

/*---------------------------------------------------------------------------------------------------*/

String GPSPROVIDER = LocationManager.GPS_PROVIDER;
private  static final long MIN_GEOGRAPHIC_POOLING_TIME_PERIOD = 10000;
private  static final float MIN_GEOGRAPHIC_POOLING_DISTANCE = (float)5.0;

public LocationManager gpsLocationManager;

static Context context = null;

BTDev	BTDevs[];
int     BTCount;

/*---------------------------------------------------------------------------------------------------*/	

class BTDev {
		String 	m_szName;
		String 	m_szAddress;
		int	m_nBTDEVType; //if 1, it's the DSCArduino Telescope Controller, if 0 it's a regular device
		
		
		BTDev(String _name, String _address) {
			m_szName = _name; m_szAddress = _address;  
		}
		BTDev(String _name, String _address, int _type) {
			m_szName = _name; m_szAddress = _address; m_nBTDEVType = _type;  
		}
	}

/*---------------------------------------------------------------------------------------------------*/

	

/*---------------------------------------------------------------------------------------------------*/
Spinner  spinner;
int objectSet;
ArrayAdapter<String> adapterMessier;
ArrayAdapter<String> adapterGroups;
TextView objectInfo;
Messier myMessiers;
int globalPos = 0;

/*---------------------------------------------------------------------------------------------------*/
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        ListView lv1 = (ListView) findViewById(R.id.ListView1);
        lv1.setCacheColorHint(0);
                
        Log.i(LOG_TAG, myBTaddr());
        
        textLatitude = (TextView) findViewById(R.id.tv_LAT);
        textLongitude = (TextView) findViewById(R.id.tv_LONG);
        
/*---------------------------------------------------------------------------------------------------*/       
   
        
        
/*---------------------------------------------------------------------------------------------------*/

    BTDevs = new BTDev[MAX_DEVICES]; 
        
       
    m_BluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    // If the adapter is null, then Bluetooth is not supported
        
    if (m_BluetoothAdapter == null) {
        Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
        finish();
        return;
    }
        
    if (!m_BluetoothAdapter.isEnabled()) 
    {
    	// enable bluetooth
        Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
    }  
        
        
    // Register for broadcasts when a device is discovered
    IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
    this.registerReceiver(mReceiver, filter);

    // Register for broadcasts when discovery has finished
    filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
    this.registerReceiver(mReceiver, filter); 
       
        
        
/*---------------------------------------------------------------------------------------------------*/
    context = this;

    /*Get a listener for GPS*/
    LocationListener gpsLocationListener = null;

    gpsLocationListener = new GpsLocationListener(this);

    /*Start Location Service for GPS*/
    gpsLocationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);

    /*Register GPS listener with Location Manager*/
    gpsLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 
    MIN_GEOGRAPHIC_POOLING_TIME_PERIOD,
    MIN_GEOGRAPHIC_POOLING_DISTANCE, gpsLocationListener);

    boolean isavailable = gpsLocationManager.isProviderEnabled(GPSPROVIDER);

        if(isavailable) {
        	Toast.makeText(context,"GPS is Enabled!", Toast.LENGTH_LONG).show();
            Location loc = gpsLocationManager.getLastKnownLocation("gps");

            if(loc != null) {
                double latitude = loc.getLatitude();
                double longitude = loc.getLongitude();
                
                //Toast.makeText(MessierMarathonActivity.this,"Longitude is  "+longitude + "   Latitude is   "+latitude, Toast.LENGTH_LONG).show();
               
                textLatitude.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);
                textLatitude.setText(Double.toString(latitude));
                textLongitude.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);
                textLongitude.setText(Double.toString(longitude));
            }
           
        }
       
/*---------------------------------------------------------------------------------------------------*/
        
 /*SpinBox Array Addapter*/       
        
        objectInfo = (TextView)findViewById(R.id.tv_Messier);
        
        spinner = (Spinner) findViewById(R.id.spinner);
       
        
        myMessiers = new Messier();
        
        spinner.requestFocus();
        
        String[] someStrings;//= new String[110];
             
        someStrings = myMessiers.GetStrings();
                
       
       
        adapterMessier = new ArrayAdapter<String>(this, R.layout.myspinnerlayout, someStrings);
        adapterMessier.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(adapterMessier);

        OnItemSelectedListener spinnerListener = new myOnItemSelectedListener(this,this.adapterGroups);
        
        spinnerListener = new myOnItemSelectedListener(this, this.adapterMessier);
        spinner.setOnItemSelectedListener(spinnerListener);
        
   
        
    }
/*---------------------------------------------------------------------------------------------------*/    
    
    
    
    public class myOnItemSelectedListener implements OnItemSelectedListener {

        /*
         * provide local instances of the mLocalAdapter and the mLocalContext
         */

        ArrayAdapter<String> mLocalAdapter;
        Activity mLocalContext;

        /**
         *  Constructor
         *  @param c - The activity that displays the Spinner.
         *  @param ad - The Adapter view that
         *    controls the Spinner.
         *  Instantiate a new listener object.
         */
        public myOnItemSelectedListener(Activity c, ArrayAdapter<String> ad) {

          this.mLocalContext = c;
          this.mLocalAdapter = ad;

        }
       
        public void onItemSelected(AdapterView<?> parent, View v, int pos, long row) {
        	
    	String str;
            
    	if( parent==spinner ){
            	str = String.format("Parent = (spinner), Objectset (%d), pos (%d), row *%d)", objectSet, pos, row);
            	Log.d("Debug", str);
            	globalPos = pos;
                   
            	if( objectSet==0 ){
        
       
        objectInfo.setText("Name: "+myMessiers.GetObjName(pos)+"  "+"RA: "+myMessiers.GetRA(pos)+"   "+"DE: "+myMessiers.GetDEC(pos)+"  "+" "+myMessiers.GetName(pos)+" "+"Magnitude:"+myMessiers.GetMagnitude(pos));
                    
                    spinner.requestFocus();
                }

            }
    
    }

	public void onNothingSelected(AdapterView<?> arg0) {
		// TODO Auto-generated method stub
		
	}
    }
    
    /*---------------------------------------------------------------------------------------------------*/  
    
    public static class GpsLocationListener implements LocationListener {


        public GpsLocationListener(Context context){

        }

        public void onLocationChanged(Location loc) {

            if (loc != null) {

                double latitude = loc.getLatitude();
                double longitude = loc.getLongitude();
                
                //Toast.makeText(context,"Please, Enable GPS and restart the application", Toast.LENGTH_LONG).show();
                //Toast.makeText(context,"Longitude is  "+longitude + "   Latitude is   "+latitude, Toast.LENGTH_LONG).show();
               
                textLatitude.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);
                textLatitude.setText(Double.toString(latitude));
                textLongitude.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);
                textLongitude.setText(Double.toString(longitude));
            }

        }//End of onLocationChanged Method

        public void onProviderDisabled(String provider) {
        	Toast.makeText(context,"GPS disabled!", Toast.LENGTH_LONG).show();
        }//End of onProviderDisabled Method

        public void onProviderEnabled(String provider) {
        	Toast.makeText(context,"GPS is ON!", Toast.LENGTH_LONG).show();
        }//End of onProviderEnabled Method

        public void onStatusChanged(String provider, int status,
                Bundle extras) {


        }//End of onStatusChanged Method

     }//End of GpsLocationListener class
     
        
    /*---------------------------------------------------------------------------------------------------*/
    
    
      
    
    public  String myBTaddr()
    {
    SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
    StringBuilder builder = new StringBuilder();
    builder.append(sharedPrefs.getString("ABTID", "00:00:00:00:00:00"));
    String ROBO_BTADDR = builder.toString();
	return ROBO_BTADDR;
    }
    /*---------------------------------------------------------------------------------------------------*/
    
    
    
	// The BroadcastReceiver that listens for discovered devices and
	// changes the title when discovery is finished
	public BroadcastReceiver mReceiver = new BroadcastReceiver() {
        //@Override
		
		
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
                        
            // When discovery finds a device
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                // Get the BluetoothDevice object from the Intent
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                //if (device.getBondState() != BluetoothDevice.BOND_BONDED) // If it's already paired, skip it, because it's been listed already
            	//-- ignore duplicates
				boolean duplicate = false;
				for (int j=0;j<BTCount;j++)
					if (BTDevs[j].m_szAddress.compareTo(device.getAddress()) == 0) { duplicate = true; break; }
				if (duplicate)
					//; //this is a duplicate
				    Toast.makeText(getBaseContext(), "Device allready exists!", Toast.LENGTH_SHORT).show();
				
				else
				{
					if (device.getAddress().compareTo(myBTaddr()) == 0)
						BTDevs[BTCount] = new BTDev(device.getName(), device.getAddress(), 1);
					else
						BTDevs[BTCount] = new BTDev(device.getName(), device.getAddress(), 0);
	                BTCount++;
				}
                
            // When discovery is finished
            } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
            	m_ASDKScanRunning = false; 
            }
            
        }
        
    };	
	
    
/*---------------------------------------------------------------------------------------------------*/
    

	/*Sending commands to arduino for future use*/ 
   
	public void onClick(View v) {
  	
	}
   
    //-----------------------------------------------------------------------------------------------
    
    
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		
		{			 int nIndex = -1, nCounter = 0;
			for (int i=0;i<BTCount;i++)
			{
				if (arg2 == nCounter) {
					nIndex = i;
					break;
				}
				nCounter++;
			}
			
                                // connect to 
			if (BTDevs[nIndex].m_nBTDEVType == 1)
			{
				//disconnect and reconnect
				Disconnect(nIndex);
				
				//connect to ROBOT
				Connect(nIndex);
				StartReadThread(nIndex);
			}
			else 
				Toast.makeText(getBaseContext(), "This is not an Arduino Telescope Controller", Toast.LENGTH_SHORT).show();


		}		
	}
	
    /*----------------------------------------------------------------------------------------------------------------------------------*/
    
	// put the /BTDEvs in the listview

	void PopulateLV()
	{
	
		ListView lv1 = (ListView) findViewById(R.id.ListView1);
		lv1.setCacheColorHint(0);
		
		ArrayList<Device> m_Devices = new ArrayList<Device>();
		Device device;
        for (int i=0;i<BTCount;i++) {
        	if (BTDevs[i].m_szAddress.compareTo(myBTaddr()) == 0) {
        		BTDevs[i].m_nBTDEVType = 1;
        		m_nRoboDev = i;
        	}
        	else 
        		BTDevs[i].m_nBTDEVType = 0;
        	    device = new Device(BTDevs[i].m_szName, 
        			BTDevs[i].m_szAddress, 
        			BTDevs[i].m_nBTDEVType,
        			0, 
        			idLVFirstItem+i);
        	m_Devices.add(device);
        }
        
    CustomAdapter lvAdapter =  new CustomAdapter(this, m_Devices);
    
    
    
    if (lvAdapter!=null) lv1.setAdapter(lvAdapter);
    
    lv1.setOnItemClickListener((OnItemClickListener) this);
             
    if (m_nRoboDev >= 0)
    	Toast.makeText(getBaseContext(), "Arduino found as " + BTDevs[m_nRoboDev].m_szAddress, Toast.LENGTH_LONG).show();
        Toast.makeText(getBaseContext(), "Tap on the selected device to connect.", Toast.LENGTH_LONG).show();
	}
	
/*----------------------------------------------------------------------------------------------------------------------------------*/

	public final boolean isInternetOn() {
    	ConnectivityManager connec =  (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
    	// ARE WE CONNECTED TO THE NET
    	if ( connec.getNetworkInfo(0).getState() == NetworkInfo.State.CONNECTED ||
    	connec.getNetworkInfo(0).getState() == NetworkInfo.State.CONNECTING ||
    	connec.getNetworkInfo(1).getState() == NetworkInfo.State.CONNECTING ||
    	connec.getNetworkInfo(1).getState() == NetworkInfo.State.CONNECTED ) {
    	// MESSAGE TO SCREEN FOR TESTING (IF REQ)
    	//Toast.makeText(this, connectionType + " connected", Toast.LENGTH_SHORT).show();
    	return true;
    	} else if ( connec.getNetworkInfo(0).getState() == NetworkInfo.State.DISCONNECTED ||  connec.getNetworkInfo(1).getState() == NetworkInfo.State.DISCONNECTED  ) {
    	//System.out.println(“Not Connected”);
    	return false;
    	}
    	return false;
    	}
	
	
/*----------------------------------------------------------------------------------------------------------------------------------*/
	
	@Override
	    public void onBackPressed() {
	        Toast.makeText(DSCArduinoActivity.this, "Please press menu for exit.", Toast.LENGTH_SHORT).show();
	       return;
	    }

	    
	    
	    public boolean onCreateOptionsMenu(Menu menu) {
	        MenuInflater inflater = getMenuInflater();
	        inflater.inflate(R.menu.menu, menu);
	        return true;
	}
	    public boolean onOptionsItemSelected(MenuItem item) {
	        switch (item.getItemId()) {

	        case R.id.settings:
				Log.d("Debug", "Settings shown");
				//unregisterReceiver(mReceiver);
	            Intent settingsActivity = new Intent(getBaseContext(), Preferences.class);
	            startActivity(settingsActivity);
	            Log.d("Debug", "Pref activity started");
	            
				break;
				
	        case R.id.toolbox:
				
	        	Intent n = new Intent(DSCArduinoActivity.this, ToolBox.class);
   	            startActivity(n);
	            
				break;
				
            case R.id.myloc:
				
            	if(isInternetOn()) {
	             	// INTERNET IS AVAILABLE, 
	             	   
	             		Toast.makeText(this, "Internet connection successfull.", Toast.LENGTH_LONG).show();
	             		Intent x = new Intent(DSCArduinoActivity.this, MyLocOnMap.class);
	       	            startActivity(x);
	       	            
	             	}else{
	             	// NO INTERNET AVAILABLE, 
	             	
	             		Toast.makeText(this, "No internet connection.", Toast.LENGTH_LONG).show();	
	             		       			
	         		    startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS));
	         			       			
	             	}
            	
	        	
	            
				break;
	        
	        case R.id.about:
	                // TODO

	                AlertDialog alertDialog;
	                alertDialog = new AlertDialog.Builder(this).create();
	                alertDialog.setTitle("DSCArduino");
	                alertDialog.setMessage("Digital Settings Circles - Developer & Astronomer - Ioannis A. Bouhras - ioannis_bouhras@zeuslinux.gr");
	                alertDialog.show();

	                break;

	        case R.id.exit:

	                // TODO
	        	   BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
	        	     if (mBluetoothAdapter == null) {
	        	     // Device does not support Bluetooth
	        	     } else {
	        	       if (!mBluetoothAdapter.isEnabled()) {
	        	        // Bluetooth is not enable :)
	
	        	    	   System.exit(0);
		   	               super.finish();   
	        	    	   
	        	     } else {
	        	    	
	        	    	 DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
	        	    		    public void onClick(DialogInterface dialog, int which) {
	        	    		        switch (which){
	        	    		        case DialogInterface.BUTTON_POSITIVE:
	        	    		            //Yes button clicked
	        	    		        	
	        	    		        	BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
	        	    		        	
	        	    		        	mBluetoothAdapter.disable();
		        	    		        	
	        	    		        	System.exit(0);
	        	    		        	     
	        	    		        	        
	        	    		        	break;

	        	    		        case DialogInterface.BUTTON_NEGATIVE:
	        	    		            //No button clicked
	        	    		        	
	        	    		        	System.exit(0);
	        			   	            
	        	    		        	
	        	    		            break;
	        	    		        }
	        	    		    }
	        	    		};

	        	    		AlertDialog.Builder builder = new AlertDialog.Builder(this);
	        	    		builder.setMessage("Disable bluetooth on exit?").setPositiveButton("Yes", dialogClickListener)
	        	    		    .setNegativeButton("No", dialogClickListener).show();
	        	    		
	        	    	 
	        	    	   
	        	       }
	        	    }
	        	
	        	   // System.exit(0);
	               // super.finish();
	                
	                break;
	        
	        case R.id.synctimebtn:
	        		        	
	        	if (m_btSck != null)
	        	try {
				
	        		
	              Toast.makeText(getBaseContext(), "Sending current time to Arduino controller", Toast.LENGTH_SHORT).show();
	    			
	    	      long time = System.currentTimeMillis() / 1000L;
	    			
	              String ptime = "T"+time;
	    			
	    	      Log.i(LOG_TAG, ": TIME send:"+ ptime);
	    			
	    	      m_btSck.getOutputStream().write(ptime.getBytes());
	    				
	        		
	        	
	              } catch (IOException e) {
		      // TODO Auto-generated catch block
			
                 		e.printStackTrace();
		      }
	        	
	        	else
	        	{
	        		Toast.makeText(getBaseContext(), "You are not connected to DSCArduino", Toast.LENGTH_SHORT).show();	
	        	}
		      break;
	                
	        case R.id.searchbtn:
	             Toast.makeText(getBaseContext(), "Scanning for devices", Toast.LENGTH_SHORT).show();
	          
		         startDiscoverBluetoothDevices();
		     break;
	        
	        case R.id.firmware:
	             
	        	 Toast.makeText(getBaseContext(), "Arduino firmware", Toast.LENGTH_SHORT).show();
	        	 if(isInternetOn()) {
	             	// INTERNET IS AVAILABLE, 
	             	   
	             		Toast.makeText(this, "Internet connection successfull.", Toast.LENGTH_LONG).show();
	             		firmwareUpdate();
	             	}else{
	             	// NO INTERNET AVAILABLE, 
	             	
	             		Toast.makeText(this, "No internet connection.", Toast.LENGTH_LONG).show();	
	             		       			
	         		    startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS));
	         			       			
	             	}
	        	 
	        	 
		     break;	
	        
	        case R.id.schematic:
	        	
	        	File FileCheck = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "DSCArduino-Schematic.png");
	        	
	        	if (FileCheck.exists()) {
	        		
	        		
	        		Toast.makeText(this, "Openning Schematic..", Toast.LENGTH_LONG).show();
	        		File file = new File("/storage/sdcard0/Pictures/DSCArduino-Schematic.png");
	        		Intent intent = new Intent(Intent.ACTION_VIEW);
	           		intent.setDataAndType(Uri.fromFile(file), "image/png");
	        		startActivity(intent);
	        		
	        		}
	        	else
	        	{
	        		m_progDlg = ProgressDialog.show(this,
	            			m_szAppTitle, "Copying schematic to SDCARD Pictures folder..",
	            			true);
	            	
	            	// Fire off a thread to do some work that we shouldn't do directly in the UI thread
	        	    Thread t = new Thread() {
	        	    	public void run() 
	        	    	{
	        	    		String newPicture = saveToSDCard(R.raw.dscarduino, "DSCArduino-Schematic.png");
	                        startMediaScanner(newPicture);
	                        m_progDlg.dismiss();	
	        	    	}
	        	    };
	        	    t.start();	
	        	
	        	    Toast.makeText(this, "Opening schematic..", Toast.LENGTH_LONG).show();
	        	    File file = new File("/storage/sdcard0/Pictures/DSCArduino-Schematic.png");
	        		Intent intent = new Intent(Intent.ACTION_VIEW);
	           		intent.setDataAndType(Uri.fromFile(file), "image/png");
	        		startActivity(intent);    	
	        	}
	        	
            break;
            
	        case R.id.donate:

	                // TODO
	            Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.paypal.com/cgi-bin/webscr?cmd=_donations&business=ioannis_bouhras%40zeuslinux%2egr&lc=US&item_name=Messier%20Application&no_note=0&currency_code=EUR&bn=PP%2dDonationsBF%3abtn_donateCC_LG%2egif%3aNonHostedGuest"));
	            startActivity(browserIntent);
	            break;

	            }
	            return true;
	}
/*----------------------------------------------------------------------------------------------------------------------------------*/    	    

public void firmwareUpdate() {
   
    Intent go_update = new Intent(this, UpdateWebScreen.class);
    go_update.putExtra(jb.astronomy.project.UpdateWebScreen.URL, 
        "http://protesilaos.no-ip.org:44844/dscarduino/firmware.html");
    startActivity(go_update); 
        	        	
        }
	    
	    

/*----------------------------------------------------------------------------------------------------------------------------------*/    	    
		
	/** Bluetooth Functions **/
	
	// not Blocking, uses events
	int ASDKDiscoverBluetoothDevices()
	{
		if (m_BluetoothAdapter.isDiscovering()) 
    		m_BluetoothAdapter.cancelDiscovery();
        
		int current_devs = BTCount;
		// Request discover from BluetoothAdapter
		
    	if (!m_BluetoothAdapter.startDiscovery()) return -1; //error
    	
    	m_ASDKScanRunning = true;

    	//  blocking operation:wait to complete
        while (m_ASDKScanRunning);
         
        return BTCount - current_devs;
	}
	/*----------------------------------------------------------------------------------------------------------------------------------*/
	
	
	final Runnable mUpdateResultsDiscover = new Runnable() {
        public void run() {
        	doneDiscoverBluetoothDevices();
        }
    };
    protected void startDiscoverBluetoothDevices() {
    	// Show Please wait dialog
    	        m_progDlg = ProgressDialog.show(this,
    			m_szAppTitle, "Scanning, please wait",
    			true);
    	
    	// Fire off a thread to do some work that we shouldn't do directly in the UI thread
	    Thread t = new Thread() {
	    	public void run() 
	    	{
	    		// blocking operation
            	m_nDiscoverResult = ASDKDiscoverBluetoothDevices();
            	//show results
	        	m_Handler.post(mUpdateResultsDiscover);
	    	}
	    };
	    t.start();
    }
    
    /*----------------------------------------------------------------------------------------------------------------------------------*/
    
    private void doneDiscoverBluetoothDevices() 
    {
    	m_progDlg.dismiss();
    	if (m_nDiscoverResult == -1)
    		Toast.makeText(getBaseContext(), "Bluetooth ERROR (is bluetooth on?)", Toast.LENGTH_LONG).show();
    	else if (m_nDiscoverResult == 0)
    		Toast.makeText(getBaseContext(), "No Bluetooth or Arduino devices found", Toast.LENGTH_LONG).show();
    	else {
    		m_nRoboDev = -1;
    		// populate
    		
			PopulateLV();
    	}
    }
    
    /*----------------------------------------------------------------------------------------------------------------------------------*/
    
    int Connect(int nIndex)
	{
		if (nIndex >= BTCount || nIndex<0) return -1; //invalid device
		
		
		
		//ANDROID SDK IMPLEMENTATION
		//--connect serial port
		BluetoothDevice ROBOBTDev = m_BluetoothAdapter.getRemoteDevice(BTDevs[nIndex].m_szAddress);
		try {
			m_btSck = ROBOBTDev.createRfcommSocketToServiceRecord(SPP_UUID);
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		try { //This is a blocking call and will only return on a successful connection or an exception
			m_btSck.connect();	             
		} catch (IOException e) {
             // Close the socket
             try { m_btSck.close();} catch (IOException e2) { e2.printStackTrace();}
             return -2; 
         }
		return 0;
	}
    
    /*----------------------------------------------------------------------------------------------------------------------------------*/
    
 int Disconnect(int nIndex)
	{
		if (nIndex >= BTCount || nIndex<0) return -1; //invalid device
		
		// DISCONNECT ASDK SOCKETS
		if (m_btSck != null) {
			try {
				m_btSck.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
            }
			m_btSck = null;
		}
		return 0;
	}

    // Worker functions
 
    private ArrayAdapter<String> mConversationArrayAdapter;
    private String mConnectedDeviceName = null;
    
    /*----------------------------------------------------------------------------------------------------------------------------------*/
    OutputStream mmOutputStream;
    InputStream mmInputStream;
    Thread workerThread;
    byte[] readBuffer;
    int readBufferPosition;
    int counter;
    volatile boolean stopWorker;
    
    void StartReadThread(final int nIndex)
    {
    	
    	ConnectionEvent(1,nIndex,null);
    	
        //final Handler handler = new Handler(); 
        final byte delimiter = 10; //This is the ASCII code for a newline character

        stopWorker = false;
        readBufferPosition = 0;
        readBuffer = new byte[2048];
        
        
        
        workerThread = new Thread(new Runnable()
        {
            public void run()
            {                
               while(!Thread.currentThread().isInterrupted() && !stopWorker)
               {
                    try 
                    {
                        int bytesAvailable = m_btSck.getInputStream().available();                        
                        if(bytesAvailable > 0)
                        {
                            byte[] packetBytes = new byte[bytesAvailable];
                            m_btSck.getInputStream().read(packetBytes);
                            for(int i=0;i<bytesAvailable;i++)
                            {
                                byte b = packetBytes[i];
                                if(b == delimiter)
                                {
                                    byte[] encodedBytes = new byte[readBufferPosition];
                                    System.arraycopy(readBuffer, 0, encodedBytes, 0, encodedBytes.length);
                                    final String data = new String(encodedBytes, "US-ASCII");
                                   
                                    readBufferPosition = 0;

                                    m_Handler.post(new Runnable()
                                    {
                                        public void run()
                                        {
                                           
                                        	//Message m = Message.obtain(m_Handler);
                                        	//m.obj = (Object)RA;
                    	                    //m_Handler.sendMessage(m);
                    	                    
                    	                    Message msg = new Message();
                    	                    msg.obj = (Object)data; // for object data
                    	                    m_Handler.sendMessage(msg);
                                        	
                                        }
                                    });
                                    
                                   
                                }
                                else
                                {
                                    readBuffer[readBufferPosition++] = b;
                                }
                            }
                        }
                    } 
                    catch (IOException ex) 
                    {
                        stopWorker = true;
                    }
               }
            }
        });

        workerThread.start();
        //return 0;
    }
   
    /*----------------------------------------------------------------------------------------------------------------------------------*/
    
    @Override
    protected void onStop()
    {
    	
        //unregisterReceiver(mReceiver);
        //unregisterReceiver(mReceiver);
    	if (mReceiver != null) {
            unregisterReceiver(mReceiver);
            mReceiver = null;
        }
        Log.i(LOG_TAG, "Unregister recievers");
        super.onStop();
    }
    
    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.v("$$$$$", "In Method: onDestroy()");

        if (mReceiver != null) {
            unregisterReceiver(mReceiver);
            mReceiver = null;
        }
    }
    
    /*----------------------------------------------------------------------------------------------------------------------------------*/ 
    

    
  
       
     
    
    final Handler m_Handler = new Handler() 
	  {
		  // Instantiating the Handler associated with the main thread.
	
	      @Override
	      public void handleMessage(Message msg) { 
	    	  
	    	  updateText((String)msg.obj);
	    
	    	  
	      }
	  
	  };
	String RAPOS;
  	String DEPOS; 
/*----------------------------------------------------------------------------------------------------------------------------------*/	  
	  private void updateText(String s)
	    {
		  final TextView mt = (TextView) findViewById(R.id.m_tvD1);
		  
	        
		    if (mt != null && s != null && s.length()>0) 
		    {
		    	int p = s.indexOf("\0332J");
		    	if (p>=0)
		    	{
		    		mt.setText("");
		    		
		    		s = s.substring(p+3);
		    	    
		    	}
		    	mt.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);
		    	mt.setText(s);
		    	//Log.i(LOG_TAG, s);
		   	 	
		    	  
		    }
		   
	    }
	  
	
	/*----------------------------------------------------------------------------------------------------------------------------------*/
	
	// Worker event function called on various events
 int ConnectionEvent(int type, int nDevId, byte buf[])
	{
		if (nDevId >= BTCount)return -1;
		
		if (type == 1) { //connected
			Toast.makeText(this, "Connected to Arduino", Toast.LENGTH_LONG).show();
			//Connect(nDevId);
		}
		if (type == 2) { //disconnect
			// DISCONNECT NATIVE SOCKETS
			Toast.makeText(this, "Disconnected from Arduino", Toast.LENGTH_LONG).show();
			Disconnect(nDevId);
			
		
		}
		
		if (type == 3) { 
			if (buf.length == 0) return -1;
			
			int nTHeader = buf[0]& 0xFF; 
			int nTType = (nTHeader >>> 4) & 0xF;	//transaction type
			int nTParam = (nTHeader) & 0xF;		//transaction parameters
			Toast.makeText(this, "Incomming data", Toast.LENGTH_LONG).show();
			
		}
		return 0;
	}

	public void nightMode()
	{
		//to be implement
		
		
		
	}
	
	//Read Firmware
	
	private String readTextFromResource(int resourceID)
	{
		InputStream raw = getResources().openRawResource(resourceID);
		ByteArrayOutputStream stream = new ByteArrayOutputStream();
		int i;
		try
		{
			i = raw.read();
			while (i != -1)
			{
				stream.write(i);
				i = raw.read();
			}
			raw.close();
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
		return stream.toString();
	}

	private String saveToSDCard(int resourceID, String finalName)
    {
        StringBuffer createdFile = new StringBuffer();

        Bitmap resourceImage = BitmapFactory.decodeResource(this.getResources(), resourceID);       
        File externalStorageFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), finalName);
        ByteArrayOutputStream bytes = new ByteArrayOutputStream(); 
        resourceImage.compress(Bitmap.CompressFormat.PNG, 100, bytes);
        byte b[] = bytes.toByteArray(); 

        try 
        {
            externalStorageFile.createNewFile(); 
            OutputStream filoutputStream = new FileOutputStream(externalStorageFile); 
            filoutputStream.write(b); 
            filoutputStream.flush(); 
            filoutputStream.close();
            createdFile.append(externalStorageFile.getAbsolutePath());
        }
        catch (IOException e)
        {
        }

        return createdFile.toString();
    }

    private void startMediaScanner(String addedPicture)
    {
         sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://"+ addedPicture)));
    }
}

	

    
